package net.xdclass.component;

import net.xdclass.strategy.ShardingDBConfig;
import net.xdclass.strategy.ShardingTableConfig;
import net.xdclass.util.CommonUtil;
import org.springframework.stereotype.Component;

@Component
public class ShortLinkComponent {

    /**
     * 62个字符
     */
    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public String createShortLinkCode(String param) {
        long murmurHash32 = CommonUtil.murmurHash32(param);
        String code = encodeToBase62(murmurHash32);

        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix(code) + code + ShardingTableConfig.getRandomTableSuffix(code);
        return shortLinkCode;
    }

    private String encodeToBase62(long num) {
        StringBuffer sb = new StringBuffer();

        do {
            int i = (int )(num%62);
            sb.append(CHARS.charAt(i));
            num = num/62;
        } while (num>0);
        String value = sb.reverse().toString();
        return value;
    }


}
